package com.example.orderfood2.managerOperate;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.orderfood2.DatabaseManager.DatabaseManager;
import com.example.orderfood2.R;
import com.example.orderfood2.Repository.ClassInfoRepository;
import com.example.orderfood2.Repository.StudentRepository;
import com.example.orderfood2.entity.Student;
import com.example.orderfood2.util.DBUtil;
import com.example.orderfood2.util.ToolsUtil;

import java.util.List;

public class AddStudentActivity extends AppCompatActivity {
    // 修改成员变量部分
    private int birthYear, birthMonth, birthDay;
    private int enrolYear, enrolMonth, enrolDay;
    private String getScience;

    private String sex = "男", class_id;
    private ClassInfoRepository dbUtil;
    private StudentRepository dbUtil1;
    //使班级列表成为全局变量
    Spinner spinner_student_class_id;

    private Student student;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 初始化数据库工具
//        dbUtil = new DBUtil(this);
        dbUtil= DatabaseManager.getInstance(this).getClassInfoRepository();
        dbUtil1= DatabaseManager.getInstance(this).getStudentRepository();
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_add_student);
        //        获取个组件
        EditText et_student_username = findViewById(R.id.et_student_username);
        EditText et_student_password = findViewById(R.id.et_student_password);
        RadioGroup student_sex = findViewById(R.id.student_sex);
        spinner_student_class_id = findViewById(R.id.spinner_student_class_id);
        EditText et_student_score = findViewById(R.id.et_student_score);
        TextView student_date = findViewById(R.id.student_date);
        TextView student_enrol = findViewById(R.id.student_enrol);
        student_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取当前日期
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                // 使用DatePickerDialog组件
                DatePickerDialog datePickerDialog = new DatePickerDialog(
                        AddStudentActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                // 格式化日期（如：yyyy-MM-dd）
                                student_date.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                                birthYear = year;
                                birthMonth = month;
                                birthDay = dayOfMonth;
                            }
                        },
                        year,
                        month,
                        day);
                datePickerDialog.show();
            }
        });
        student_enrol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 获取当前日期
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                // 使用DatePickerDialog组件
                DatePickerDialog datePickerDialog = new DatePickerDialog(
                        AddStudentActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                                // 格式化日期（如：yyyy-MM-dd）
                                student_enrol.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                                enrolYear = year;
                                enrolMonth = month;
                                enrolDay = dayOfMonth;
                            }
                        },
                        year,
                        month,
                        day);
                datePickerDialog.show();
            }
        });
        // 加载班级数据
        loadClassData();
        // 设置 RadioGroup 的选中状态改变监听器
        student_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                sex = radioButton.getText().toString();
            }
        });

        //     // 设置班级的选中状态改变监听器
        spinner_student_class_id.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
//获取值
                class_id=(String) adapterView.getItemAtPosition(position);

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                Toast.makeText(AddStudentActivity.this, "请选择班级", Toast.LENGTH_SHORT).show();
            }
        });
        //提交表单
        Button submit=findViewById(R.id.student_submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //拼接生日和入学日期
                String birthday=birthYear+"-"+birthMonth+"-"+birthDay;
                String enrollDate=enrolYear+"-"+enrolMonth+"-"+enrolDay;
                //转换为字符串
                String username= ToolsUtil.editTextToString(et_student_username);
                String password=ToolsUtil.editTextToString(et_student_password);
                String score=ToolsUtil.editTextToString(et_student_score);
                //添加学生
                if(username.isEmpty()||password.isEmpty()||score.isEmpty()||birthday.equals("0-0-0")||enrollDate.equals("0-0-0")){
                    Toast.makeText(AddStudentActivity.this, "请完整填写表单", Toast.LENGTH_SHORT).show();
                }else {
                    //创建学生实体类
                    student=new Student(null,username,password,sex,class_id,score,birthday,enrollDate);
                    //调用DBUtil添加学生
                    long result=dbUtil1.registerStudent(student);
                    if(result!=-1){
                        Toast.makeText(AddStudentActivity.this, "学生:"+username+"添加成功", Toast.LENGTH_SHORT).show();
                        et_student_username.setText("");
                        et_student_password.setText("");
                        et_student_score.setText("");
                        student_date.setText("请选择日期");
                        student_enrol.setText("请选择日期");

                    }else {
                        Toast.makeText(AddStudentActivity.this, "添加失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void loadClassData() {
        List<String> classNumbers;
        if(getIntent().getStringExtra("science")==null){
            // 从数据库获取班级信息
            classNumbers = dbUtil.QueryClassInfo();
        }
        else {
            // 从数据库获取班级信息
            classNumbers = dbUtil.TeacherQueryClassInfo(getIntent().getStringExtra("science"));
        }
        // 创建适配器,用于将数组或列表数据绑定到视图组件（如 Spinner、ListView 等）上
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                //定义每个项（item）的布局
                android.R.layout.simple_spinner_item,
                classNumbers
        );
        // 设置下拉菜单样式
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 应用适配器到Spinner
        spinner_student_class_id.setAdapter(adapter);
    }


}